package com.xinrui.sunnyday.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xinrui.sunnyday.constant.MessageConstant;
import com.xinrui.sunnyday.entity.Result;
import com.xinrui.sunnyday.pojo.OrderSetting;
import com.xinrui.sunnyday.service.OrdersettingService;
import com.xinrui.sunnyday.utils.POIUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/ordersetting")
public class OrdersettingController {

    @Reference
    private OrdersettingService ordersettingService;

    /**
     * 上传模板
     * @param excelFile
     * @return
     */
    @RequestMapping("/upload")
    public Result upload(MultipartFile excelFile) {
        try {
//            通过工具类读取到Excel表中的数据
            List<String[]> list = POIUtils.readExcel(excelFile);
//            将数据转换为对应格式后封装为对象并保存到集合中
            List<OrderSetting> orderSettings = new ArrayList<>();
//            创建SimpleDateFormat对象用于转换日期格式
            SimpleDateFormat dateFormat = new SimpleDateFormat(POIUtils.DATE_FORMAT);

//            用于转换数据类型
            Date date = null;
            int number = 0;

            for (String[] strings : list) {
//                将Excel表中的数据转换为对象所对应的数据类型
                date = dateFormat.parse(strings[0]);
                number = Integer.parseInt(strings[1]);
//                封装到对象并保存到集合
                orderSettings.add(new OrderSetting(date, number));
            }
//            添加数据
            ordersettingService.add(orderSettings);
            return new Result(true, MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
        } catch (IOException | ParseException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.IMPORT_ORDERSETTING_FAIL);
        }
    }

    /**
     * 根据月份查询日期
     * @param month
     * @return
     */
    @GetMapping("/findDataByMonth")
    public Result findDataByMonth(String month) {
        List<Map<String, Integer>> list = ordersettingService.findDataByMonth(month);
        return new Result(true, MessageConstant.GET_ORDERSETTING_SUCCESS, list);
    }

    /**
     * 修改
     * @param orderSetting
     * @return
     */
    @PostMapping("/update")
    public Result update(@RequestBody OrderSetting orderSetting) {
        ordersettingService.update(orderSetting);
        return new Result(true, MessageConstant.ORDERSETTING_SUCCESS);
    }
}
